package com.weifly.weistock.module.stockmonitor.impl;

import com.weifly.weistock.core.market.bo.StockKLineBO;
import com.weifly.weistock.core.monitor.AbstractMonitorService;
import com.weifly.weistock.module.stockmonitor.StockMonitorHoldService;
import com.weifly.weistock.module.stockmonitor.StockMonitorStoreService;
import com.weifly.weistock.module.stockmonitor.bo.StockMonitorConfigBO;
import com.weifly.weistock.module.stockmonitor.bo.StockMonitorDayBO;
import com.weifly.weistock.module.stockmonitor.bo.StockMonitorHoldBO;

import java.util.*;

/**
 * 股票监控hold服务
 *
 * @author weifly
 * @since 2021/6/30
 */
public class StockMonitorHoldServiceImpl extends AbstractMonitorService implements StockMonitorHoldService {

    private SortedMap<String, StockMonitorHoldBO> stockMonitorHoldMap = new TreeMap<>(); // key有序的map

    private StockMonitorStoreService stockMonitorStoreService;

    public void setStockMonitorStoreService(StockMonitorStoreService stockMonitorStoreService) {
        this.stockMonitorStoreService = stockMonitorStoreService;
    }

    @Override
    public void updateStockMonitorList(List<StockMonitorConfigBO> stockMonitorConfigList) {
        synchronized (this) {
            this.stockMonitorHoldMap.clear();
            for (StockMonitorConfigBO stockMonitorConfig : stockMonitorConfigList) {
                this.stockMonitorHoldMap.put(stockMonitorConfig.getStockCode(), new StockMonitorHoldBO(stockMonitorConfig));
            }
        }
    }

    @Override
    public void calcStockMonitor(StockKLineBO stockKLine, String tradeStockCode) {
        StockMonitorConfigBO monitorConfig = new StockMonitorConfigBO();
        monitorConfig.setStockCode(stockKLine.getStockCode());
        monitorConfig.setStockName(stockKLine.getStockName());
        monitorConfig.setStockCatalog(stockKLine.getStockCatalog());
        monitorConfig.setTradeStockCode(tradeStockCode);
        Map<String, StockMonitorDayBO> dayMap = new StockMonitorConfigCalculator(stockKLine.getDayList()).calc();
        monitorConfig.getDayList().addAll(dayMap.values());
        // 保存
        this.stockMonitorStoreService.saveStockMonitorConfig(monitorConfig);
        // 更新缓存
        synchronized (this) {
            this.stockMonitorHoldMap.put(stockKLine.getStockCode(), new StockMonitorHoldBO(monitorConfig));
        }
    }

    @Override
    public List<StockMonitorHoldBO> getStockList() {
        synchronized (this) {
            return new ArrayList<>(this.stockMonitorHoldMap.values());
        }
    }

    @Override
    public StockMonitorHoldBO getStock(String stockCode) {
        synchronized (this) {
            return this.stockMonitorHoldMap.get(stockCode);
        }
    }
}
